<script setup name="AsModal">
  const sVxeModal = ref()
  const modelValue = defineModel()

  const defaultConfig = ref({
    mask: false,
    lockView: false,
    showZoom: true,
    resize: true,
    destroyOnClose: true,
    showFooter: true,
  })
  const emit = defineEmits(['resize', 'zoom'])
  const attrs = useAttrs()
  const modalWidth = ref(attrs.width)

  provide('modalWidth', modalWidth)

  function debounce(fn, delay) {
    var timer
    return function () {
      var context = this
      var args = arguments
      clearTimeout(timer)
      timer = setTimeout(function () {
        fn.apply(context, args)
      }, delay)
    }
  }

  const resize = debounce((params) => {
    modalWidth.value = ~~params.$modal.getBox().style.width.replace(/px$/, '')
    emit('resize', params)
  }, 16)

  const zoom = (params) => {
    if (params.type == 'maximize') {
      modalWidth.value = modalWidth.value = window.innerWidth - 12
    } else {
      modalWidth.value = ~~params.$modal.getBox().style.width.replace(/px$/, '')
    }
    emit('zoom', params)
  }

  defineExpose({ sVxeModal, resize })
</script>

<template>
  <vxe-modal ref="sVxeModal" v-model="modelValue" v-bind="{ ...$attrs, ...defaultConfig }" @resize="resize" @zoom="zoom">
    <template v-for="(_, slot) in $slots" #[slot]="slotProps" :key="slot">
      <div><slot :name="slot" v-bind="slotProps ?? {}"></slot></div>
    </template>
  </vxe-modal>
</template>

<style lang="css" scoped>
  .s-preview-modal {
  }
</style>
